//
//  CTPopMenuView.m
//  IBDP
//
//  Created by cattsoft on 2017/7/14.
//  Copyright © 2017年 cattsoft. All rights reserved.
//

#import "CTPopMenuView.h"
#import "CTPopMenuTableViewCell.h"
#import "CTPopMenuManager.h"
#import "CTPopMenuModel.h"


static const CGFloat triangleHeight = 10.0f;
static const CGFloat margin = 10.0f;

@interface CTPopMenuView()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) NSArray *dataArr;

@property (nonatomic,assign) CGPoint startPoint;

@end

@implementation CTPopMenuView

- (instancetype)initWithView:(UIView *)view itemWidth:(CGFloat)width itemHeight:(CGFloat)height items:(NSArray *)itemArr style:(CTPopMenuStyle *)menuStyle {
    if (self = [super init]) {
        _menuStyle = menuStyle;
        self.backgroundColor = [_menuStyle.maskedColor colorWithAlphaComponent:self.menuStyle.maskedAlpha];
        if (height > 0) {
           _cellHeight = height;
        }else {
            _cellHeight = 40;
        }
        if (width > 0) {
            _menuWidth = width;
        }else {
            _menuWidth = 150;
        }
        _menuStyle.cellHeight = _cellHeight;
        _dismissed = YES;
        int height = _cellHeight * itemArr.count;
        if (height > 400) {
            height = 400;
        }
        CGPoint centerPoint = view.center;
        float viewMaxY = [view convertRect:view.bounds toView:view.window].origin.y + view.frame.size.height;
        CGFloat tableViewY = viewMaxY + margin;
        CGFloat tableViewX = centerPoint.x - _menuWidth/2;

        //左边
        if (tableViewX <=5) {
           tableViewX = 5;
        }
        //右边
        if (tableViewX + _menuWidth >=CTSCREEN_W-5) {
            tableViewX = [UIScreen mainScreen].bounds.size.width - margin - _menuWidth ;
        }
        _startPoint = CGPointMake(centerPoint.x, [view convertRect:view.bounds toView:view.window].origin.y + view.frame.size.height);
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(tableViewX, tableViewY, _menuWidth, height+2) style:UITableViewStylePlain];
        _tableView.backgroundColor = _menuStyle.menuColor;
        _tableView.layer.cornerRadius = 3.5f;
        _tableView.layer.masksToBounds = YES;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.bounces = NO;
        _tableView.tableFooterView = [UIView new];
        _tableView.tableHeaderView = [UIView new];
        _tableView.rowHeight = _menuStyle.cellHeight;
        if (centerPoint.x> CTSCREEN_W /2) {
            _tableView.layer.anchorPoint =  CGPointMake(1.0f, 0.0f);
            _tableView.layer.position = CGPointMake(tableViewX + _menuWidth,tableViewY);
        }else{
            _tableView.layer.anchorPoint = CGPointMake(0.0f, 0.0f);
            _tableView.layer.position = CGPointMake(tableViewX,tableViewY);
        }
        _tableView.transform = CGAffineTransformMakeScale(0.001, 0.001);
        
        _dataArr = itemArr;
        [self addSubview:_tableView];
        [self drawTriangleLayer];
    }
    return self;
}

#pragma mark 绘制尖头
- (void)drawTriangleLayer {
    CGFloat triangleLength = triangleHeight * 2.0 / 1.732;
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:_startPoint];
    [path addLineToPoint:CGPointMake(_startPoint.x - triangleLength * 0.5, _startPoint.y + triangleHeight)];
    [path addLineToPoint:CGPointMake(_startPoint.x + triangleLength * 0.5, _startPoint.y + triangleHeight)];
    CAShapeLayer *triangleLayer = [CAShapeLayer layer];
    triangleLayer.path = path.CGPath;
    triangleLayer.fillColor = self.menuStyle.menuColor.CGColor;
    triangleLayer.strokeColor = self.menuStyle.menuColor.CGColor;
    self.triangleLayer = triangleLayer;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.layer addSublayer:triangleLayer];
    });
}

- (void)setMenuWidth:(CGFloat)menuWidth{
    _menuWidth = menuWidth;
}

- (void)setCellHeight:(CGFloat)cellHeight{
    _cellHeight = cellHeight;
    _tableView.rowHeight = _cellHeight;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [CTPopMenuManager dismiss];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CTPopMenuTableViewCell *cell = [[CTPopMenuTableViewCell alloc] initWithTableView:tableView popMenuModel:self.dataArr[indexPath.row] style:self.menuStyle];
    cell.contentView.backgroundColor = self.menuStyle.menuColor;
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self tableView:tableView didDeselectRowAtIndexPath:indexPath];
    if ([self.delegate respondsToSelector:@selector(CTPopMenuView:didSelectRow:)]) {
        [self.delegate CTPopMenuView:self didSelectRow:indexPath.row];
        [CTPopMenuManager dismiss];
    }
    if (self.clickAction) {
        self.clickAction(indexPath.row);
        [CTPopMenuManager dismiss];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

@end
